import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';

import 'MainToolPage.dart';

/*
 * 封装 restful 请求
 *
 * GET、POST、DELETE、PATCH
 * 主要作用为统一处理相关事务：
 *  - 统一处理请求前缀；
 *  - 统一打印请求信息；
 *  - 统一打印响应信息；
 *  - 统一打印报错信息；
 */
class DioUtils {
  /// global dio object
  static Dio dio;

  /// default options
  static const String API_PREFIX = 'http://fengxing.581vv.com/api/';
  static const int CONNECT_TIMEOUT = 10000;
  static const int RECEIVE_TIMEOUT = 3000;

  /// http request methods
  static const String GET = 'get';
  static const String POST = 'post';
  static const String PUT = 'put';
  static const String PATCH = 'patch';
  static const String DELETE = 'delete';

  ///Get请求测试
  static void getHttp() async {
    try {
      Response response = await Dio().get("http://www.google.cn");
      print("response$response");
    } on DioError catch (e) {
      print('请求出错：' + e.toString());
      showError(e);
    }
  }

  ///Post请求测试
  static void noTokenPostHttp<T>(
    BuildContext context,
    String url, {
    Function(Map t) onSuccess,
    Function(String error) onError,
  }) async {
    url = API_PREFIX + url;
    print("请求接口$url");

    try {
      Response response;
      Dio dio = createInstance();
      response = await dio.post(url);
      if (response.statusCode == 200) {
        if (onSuccess != null) {
          // onSuccess(response.data);
          onSuccess(json.decode(response.data));
        }
      } else if (response.statusCode == 201) {
        // showloginout(context);
      } else {
        onError("请求失败");
        throw Exception('statusCode:${response.statusCode}');
      }
      print('返回数据：' + response.toString());
    } on DioError catch (e) {
      print('请求出错：' + e.toString());
      onError(e.toString());
      showError(e);
    }
  }

  ///Post请求测试
  static void postHttp<T>(
    BuildContext context,
    String url, {
    parameters,
    Function(Map t) onSuccess,
    Function(String error) onError,
  }) async {
    url = API_PREFIX + url;
    print("请求接口$url");

    ///定义请求参数
    parameters = parameters ?? {};
    print("请求参数$parameters");
    //参数处理
    parameters.forEach((key, value) {
      if (url.indexOf(key) != -1) {
        url = url.replaceAll(':$key', value.toString());
      }
    });

    try {
      Response response;
      Dio dio = createInstance();
      response =
          await dio.post(url, data: parameters, queryParameters: parameters);
      if (response.statusCode == 200) {
        if (onSuccess != null) {
          // onSuccess(response.data);
          onSuccess(json.decode(response.data));
        }
      } else if (response.statusCode == 201) {
        // showloginout(context);
      } else {
        onError("请求失败");
        throw Exception('statusCode:${response.statusCode}');
      }
      print('返回数据：' + response.toString());
    } on DioError catch (e) {
      print('请求出错：' + e.toString());
      onError(e.toString());
      showError(e);
    }
  }

  ///Post请求测试
  static void postOneImageHttp<T>(
    BuildContext context,
    String url, {
    parameters,
    imageFile,
    Function(Map t) onSuccess,
    Function(String error) onError,
  }) async {
    url = API_PREFIX + url;
    print("请求接口$url");

    ///定义请求参数
    parameters = parameters ?? {};
    print("请求参数$parameters");
    //参数处理
    parameters.forEach((key, value) {
      if (url.indexOf(key) != -1) {
        url = url.replaceAll(':$key', value.toString());
      }
    });

    try {
      Response response;
      Dio dio = createInstance();
      List<MultipartFile> list = [];

      MultipartFile multipartFile = await MultipartFile.fromFile(
        imageFile,
        filename: '${DateTime.now().millisecondsSinceEpoch}some-file-name0.jpg',
      );
      list.add(multipartFile);
      FormData formData = FormData.fromMap({"file": list});
      response =
          await dio.post(url, data: formData, queryParameters: parameters);

      if (response.statusCode == 200) {
        if (onSuccess != null) {
          // onSuccess(response.data);
          onSuccess(json.decode(response.data));
        }
      } else {
        onError("请求失败");
        throw Exception('statusCode:${response.statusCode}');
      }
      print('返回数据：' + response.toString());
    } on DioError catch (e) {
      print('请求出错：' + e.toString());
      onError(e.toString());
      showError(e);
    }
  }

  ///Post请求测试
  static void postImageHttp<T>(
    BuildContext context,
    String url, {
    parameters,
    images,
    Function(Map t) onSuccess,
    Function(String error) onError,
  }) async {
    url = API_PREFIX + url;
    print("请求接口$url");

    ///定义请求参数
    parameters = parameters ?? {};
    print("请求参数$parameters");
    //参数处理
    parameters.forEach((key, value) {
      if (url.indexOf(key) != -1) {
        url = url.replaceAll(':$key', value.toString());
      }
    });

    try {
      Response response;
      Dio dio = createInstance();
      List<MultipartFile> list = [];
      for (int i = 0; i < images.length; i++) {
        ByteData byteData = await images[i].getByteData();
        List<int> imageData = byteData.buffer.asUint8List();

        MultipartFile multipartFile = MultipartFile.fromBytes(
          imageData,
          filename:
              '${DateTime.now().millisecondsSinceEpoch}some-file-name$i.jpg',
          // contentType: MediaType("image", "jpg"),
        );
        list.add(multipartFile);
      }
      FormData formData = FormData.fromMap({"file": list});
      // response =
      //     await dio.post(url, data: formData, queryParameters: parameters);
      response = ObjectUtil.isEmpty(parameters)
          ? await dio.post(url, data: formData)
          : await dio.post(url, data: formData, queryParameters: parameters);

      if (response.statusCode == 200) {
        if (onSuccess != null) {
          // onSuccess(response.data);
          onSuccess(json.decode(response.data));
        }
      } else {
        onError("请求失败");
        throw Exception('statusCode:${response.statusCode}');
      }
      print('返回数据：' + response.toString());
    } on DioError catch (e) {
      print('请求出错：' + e.toString());
      onError(e.toString());
      showError(e);
    }
  }

  /// request method
  //url 请求链接
  //parameters 请求参数
  //metthod 请求方式
  //onSuccess 成功回调
  //onError 失败回调
  static Future<Map> request<T>(String url,
      {parameters,
      method,
      Function(T t) onSuccess,
      Function(String error) onError}) async {
    parameters = parameters ?? {};
    method = method ?? 'GET';

    /// 请求处理
    parameters.forEach((key, value) {
      if (url.indexOf(key) != -1) {
        url = url.replaceAll(':$key', value.toString());
      }
    });

    /// 打印:请求地址-请求方式-请求参数
    print('请求地址：【' + method + '  ' + url + '】');
    print('请求参数：' + parameters.toString());

    Dio dio = createInstance();
    //请求结果
    var result;
    try {
      Response response = await dio.request(url,
          data: parameters, options: new Options(method: method));
      result = response.data;
      if (response.statusCode == 200) {
        if (onSuccess != null) {
          onSuccess(result);
        }
      } else {
        throw Exception('statusCode:${response.statusCode}');
      }
      print('返回数据：' + response.toString());
    } on DioError catch (e) {
      print('请求出错：' + e.toString());
      showError(e);
    }

    return result;
  }

  /// 创建 dio 实例对象
  static Dio createInstance() {
    if (dio == null) {
      /// 全局属性：请求前缀、连接超时时间、响应超时时间
      var options = BaseOptions(
        connectTimeout: 15000,
        receiveTimeout: 15000,
        responseType: ResponseType.plain,
        validateStatus: (status) {
          // 不使用http状态码判断状态，使用AdapterInterceptor来处理（适用于标准REST风格）
          return true;
        },
        baseUrl: "http://poetry.huhustory.com/",
      );

      dio = new Dio(options);
    }

    return dio;
  }

  /// 清空 dio 对象
  static clear() {
    dio = null;
  }
}

showError(DioError e) {
  if (e.type == DioErrorType.CONNECT_TIMEOUT) {
    showToast("请求超时");
  } else if (e.type == DioErrorType.SEND_TIMEOUT) {
    showToast("请求超时");
  } else if (e.type == DioErrorType.RECEIVE_TIMEOUT) {
    showToast("请求超时");
  } else if (e.type == DioErrorType.RESPONSE) {
    showToast("请求失败");
  } else if (e.type == DioErrorType.CANCEL) {
    showToast("请求取消");
  } else if (e.type == DioErrorType.DEFAULT) {
    showToast("网络异常,请检查网络");
  } else {}
}

// Future showloginout(BuildContext context) {
//   return showCupertinoDialog(
//     context: context,
//     builder: (context) {
//       return CupertinoAlertDialog(
//         title: Text('提示'),
//         content: Text(
//           '您的账号已在其他设备登录',
//           style: TextStyle(
//             color: Color(0xFF333333),
//             fontSize: 16,
//           ),
//         ),
//         actions: <Widget>[
//           CupertinoActionSheetAction(
//             child: Text(
//               '确定',
//               style: TextStyle(
//                 color: Color(0xFF1C80F8),
//                 fontSize: 16,
//               ),
//             ),
//             onPressed: () {
//               setData("token", "");
//               Navigator.pushAndRemoveUntil(
//                   context,
//                   MaterialPageRoute(builder: (context) => LoginPage()),
//                   (route) => false);
//             },
//             isDefaultAction: true,
//           ),
//         ],
//       );
//     },
//   );
// }
